import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

import { IOrderItem, OrderItem } from 'app/shared/model/order-item.model';
import { OrderItemService } from './order-item.service';

@Component({
  selector: 'jhi-order-item-update',
  templateUrl: './order-item-update.component.html',
})
export class OrderItemUpdateComponent implements OnInit {
  isSaving = false;

  editForm = this.fb.group({
    id: [],
    orderId: [],
    itemId: [],
    itemCode: [],
    itemName: [],
    itemTypeId: [],
    itemTypeName: [],
    offset: [],
    shortProfile: [],
    profile: [],
  });

  constructor(protected orderItemService: OrderItemService, protected activatedRoute: ActivatedRoute, private fb: FormBuilder) {}

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ orderItem }) => {
      this.updateForm(orderItem);
    });
  }

  updateForm(orderItem: IOrderItem): void {
    this.editForm.patchValue({
      id: orderItem.id,
      orderId: orderItem.orderId,
      itemId: orderItem.itemId,
      itemCode: orderItem.itemCode,
      itemName: orderItem.itemName,
      itemTypeId: orderItem.itemTypeId,
      itemTypeName: orderItem.itemTypeName,
      offset: orderItem.offset,
      shortProfile: orderItem.shortProfile,
      profile: orderItem.profile,
    });
  }

  previousState(): void {
    window.history.back();
  }

  save(): void {
    this.isSaving = true;
    const orderItem = this.createFromForm();
    if (orderItem.id !== undefined) {
      this.subscribeToSaveResponse(this.orderItemService.update(orderItem));
    } else {
      this.subscribeToSaveResponse(this.orderItemService.create(orderItem));
    }
  }

  private createFromForm(): IOrderItem {
    return {
      ...new OrderItem(),
      id: this.editForm.get(['id'])!.value,
      orderId: this.editForm.get(['orderId'])!.value,
      itemId: this.editForm.get(['itemId'])!.value,
      itemCode: this.editForm.get(['itemCode'])!.value,
      itemName: this.editForm.get(['itemName'])!.value,
      itemTypeId: this.editForm.get(['itemTypeId'])!.value,
      itemTypeName: this.editForm.get(['itemTypeName'])!.value,
      offset: this.editForm.get(['offset'])!.value,
      shortProfile: this.editForm.get(['shortProfile'])!.value,
      profile: this.editForm.get(['profile'])!.value,
    };
  }

  protected subscribeToSaveResponse(result: Observable<HttpResponse<IOrderItem>>): void {
    result.subscribe(
      () => this.onSaveSuccess(),
      () => this.onSaveError()
    );
  }

  protected onSaveSuccess(): void {
    this.isSaving = false;
    this.previousState();
  }

  protected onSaveError(): void {
    this.isSaving = false;
  }
}
